package com.zc.demo.controller;

import com.zc.demo.model.BookInfo;
import com.zc.demo.service.BookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RequestMapping("/book")
@RestController
public class BookController {
    @Autowired
    private BookService bookService;
    /**
     * 1、获取数据库图书信息
     */
    @RequestMapping("/getlist")
    public List<BookInfo> getlist(){
        return bookService.getListBookInfo();
    }

    /**
     * 2、添加图书
     */
    @RequestMapping("/addBook")
    public String addBook(@RequestBody BookInfo bookInfo){
        log.info("Received book: {}", bookInfo);
        //检查
        if(!StringUtils.hasLength(bookInfo.getBookName())
        || !StringUtils.hasLength(bookInfo.getAuthor())
        || bookInfo.getCount()==null
        || !StringUtils.hasLength(bookInfo.getBookTypes())
        || bookInfo.getPrice()==null
        || !StringUtils.hasLength(bookInfo.getPublishName())
        || bookInfo.getStatus()==null
        || !StringUtils.hasLength(bookInfo.getBookDesc())){
            return "输入数据不合法，请检查输入数据！";
        }
        try {
            bookService.addBook(bookInfo);
            return "";//成功返回空
        }catch (Exception e){
            log.error("添加图书失败！",e);
            return e.getMessage();
        }
    }
}
